from django import template
from django.contrib.contenttypes.models import ContentType
from ..models import LikeNum, LikeRecord

register = template.Library()

@register.simple_tag
def get_liked_num(obj):
    content_type = ContentType.objects.get_for_model(obj)
    like_count, created = LikeNum.objects.get_or_create(content_type=content_type, object_id=obj.pk)
    return like_count.liked_num

@register.simple_tag(takes_context=True)
def get_like_status(context, obj):
    '''
    根据用户当前状态，获取点赞应该显示的状态
    '''
    user = context['user']
    if user.is_authenticated:
        content_type = ContentType.objects.get_for_model(obj)
        if LikeRecord.objects.filter(content_type=content_type, object_id=obj.pk, user=user).exists():
            return 'active'
    return ''

@register.simple_tag
def get_content_type(obj):
    ct = ContentType.objects.get_for_model(obj)
    return ct.model